import {
    colorUISdk
} from "../../config/mp-sdk";
import {updateCurrentPageShare} from "../../mp-sdk/lib/share";

const app = getApp();
let hasShowedOnce = false;

Page({
    data: {
        scrollTop: 0,
        phoneNumber: "13526264379",
        swiperList: [{
            img: "/static/img/45fc.png"
        },
            {
                img: "/static/img/d0f2.png"
            }
        ],
        target: '',
        latitude: '',
        longitude: '',
        qrcodeInfo: {},
        modalBox: {},
        notify: {
            show: false,
            msg: "",
            bg: "bg-red",
            type: 3,
            align: '',
        },
        modal: {
            show: false,
            title: '',
            content: ""
        },
        subscribe_modal: {
            show: false,
            title: '',
            content: ""
        },
        send_mode: {
            phone: '',
            send_msg: '老登,过来挪个车呗~',
        }
    },
    goToBuy() {
        wx.navigateTo({
            url: '/pages/yd_product/home'
        })
    },
    onLoad(options) {
        let qrcode_id = null;
        let user_id = null;
        // scene 是经过 URL 编码的，需要手动解析
        if (options.scene) {
            const sceneParams = decodeURIComponent(options.scene);
            // 转换成对象
            const params = {};
            sceneParams.split('&').forEach(kv => {
                const [key, value] = kv.split('=');
                params[key] = value;
            });
            qrcode_id = params.qrcode_id;
            user_id = params.user_id;
        }
        //获取手机号
        this.getPhoneNumber();
        if (qrcode_id) {
            //获取小程序码的信息
            this.getQrcodeDetail(qrcode_id);
        } else {
            if (user_id) {
                this.getTestQrcodeDetail(user_id);
            }

            //跳转到主页
            console.log('跳转到主页')
        }
    },
    onShow() {
        if (!hasShowedOnce) {
            hasShowedOnce = true;
            return;  // 第一次进入不执行
        }
        this.getUserInfo();
       /* if (app.userInfo && Object.keys(app.userInfo).length > 0) {
            this.setData({
                userInfo: app.userInfo
            });
        } else {
            this.getUserInfo();
        }*/
    },
    onHide() {
        //清空数据
        this.setData({
            qrcodeInfo: {}
        });
    },

    changeWxNotice(e) {
        if (e.detail) {
            this.subscribe();
        } else {
            colorUISdk.request({
                url: 'api/user/change_wx_notice',
                method: 'POST',
                data: {
                    wx_notice: 0
                }
            }).then(res => {
                if (res.code === 1) {
                    this.setData({userInfo: this.formatUserInfo(res.data)});
                    wx.showToast({title: res.msg, icon: 'success'});
                } else {
                    wx.showToast({title: res.msg, icon: 'none'});
                }
            });
        }
    },
    getUserInfo() {
        colorUISdk.request({
            url: 'api/user/info',
            method: 'GET',
            data: {}
        }).then(res => {
            if (res && res.code === 1) {
                this.setUserInfo(res.data);
                // 登录成功后立即更新分享配置
                updateCurrentPageShare();
            } else {
                wx.showToast({title: res.msg || '获取失败', icon: 'none'});
            }
        }).catch(err => {
            console.error(err);
            wx.showToast({title: '系统异常', icon: 'none'});
        });
    },
    setUserInfo(data) {
        this.setData({
            userInfo: this.formatUserInfo(data)
        });
        app.userInfo = this.data.userInfo;
    },
    // 格式化接口返回数据，避免空值错误
    formatUserInfo(data) {
        return {
            id: data.id || '',
            avatar: data.avatar || '',
            nickname: data.nickname || '',
            carQrcode: Array.isArray(data.carQrcode) ? data.carQrcode : [],
            wx_notice: data.wx_notice || 0,
            group_img: data.group_img || '',
            phone: data.phone || '',
            backup_phone: data.backup_phone || '',
            is_privacy: data.is_privacy || 1,
            qrcode_url: data.qrcode_url || '',
            is_bind: data.is_bind || false,
            can_withdraw: data.can_withdraw || 0.00,
            pending_amount: data.pending_amount || 0.00,
        };
    },

    //获取小程序码的信息  api/user/get_qrcode_details
    getQrcodeDetail(qrcode_id) {
        console.log('获取小程序码的信息');

        colorUISdk.request({
            url: 'api/user/get_qrcode_details',
            method: 'GET',
            data: {
                qrcode_id: qrcode_id
            }
        }).then(res => {
            //判断
            if (res.code === 1) {
                let qrcodeInfo = res.data;

                //已经停用
                if (qrcodeInfo.status === 3) {
                    wx.showToast({
                        title: '该挪车码已停用',
                        icon: 'none'
                    })
                    this.setData({
                        qrcodeInfo: qrcodeInfo
                    });
                }

                //增加扫码记录
                colorUISdk.request({
                    url: 'api/user/set_scan_record',
                    method: 'POST',
                    data: {
                        qrcode: qrcode_id,
                        type: 1,
                        pid: qrcodeInfo.user_id
                    }
                })

                //正在使用
                if (qrcodeInfo.status === 2) {
                    this.setData({
                        qrcodeInfo: qrcodeInfo
                    });
                }

                //待绑定
                if (qrcodeInfo.status === 1) {
                    this.setData({
                        qrcodeInfo: qrcodeInfo
                    });
                    this.setData({
                        modalBox: {
                            qrcode_id: qrcodeInfo.id,
                            phone: qrcodeInfo.phone,
                            backup_phone: qrcodeInfo.backup_phone,
                            is_privacy: qrcodeInfo.is_privacy,
                            wx_notice: qrcodeInfo.wx_notice
                        }
                    });
                }
            }
        }).catch(err => {
            wx.showToast({
                title: '无效的小程序码',
                icon: 'none'
            })
        })


    },

    //通过参数获取体验码信息
    getTestQrcodeDetail(user_id) {

        colorUISdk.request({
            url: 'api/user/get_test_qrcode_details',
            method: 'GET',
            data: {
                user_id: user_id
            }
        }).then(res => {

            //判断
            if (res.code === 1) {
                let otherUser = res.data;
                //待绑定
                if (otherUser.is_bind === 1) {
                    this.setData({
                        qrcodeInfo: {
                            qrcode_id: otherUser.id,
                            id: otherUser.id,
                            user_id: user_id,
                            phone: otherUser.phone,
                            backup_phone: otherUser.backup_phone,
                            is_privacy: otherUser.is_privacy,
                            wx_notice: otherUser.wx_notice,
                            status: 2,
                        }
                    });

                    //增加扫码记录
                    colorUISdk.request({
                        url: 'api/user/set_scan_record',
                        method: 'POST',
                        data: {
                            qrcode: null,
                            type: 2,
                            pid: user_id
                        }
                    })

                } else {
                    wx.showToast({
                        title: '车主已关闭该体验版挪车码',
                        icon: 'none'
                    })
                }
            }
        }).catch(err => {
            wx.showToast({
                title: '无效的小程序码',
                icon: 'none'
            })
        })


    },

    onInputChange(e) {
        const key = e.currentTarget.dataset.key;
        const field = e.currentTarget.dataset.field;
        const value = e.detail.value;
        this.setData({
            [`${key}.${field}`]: value
        });
    },

    onSwitchChange(e) {
        const field = e.currentTarget.dataset.field;
        let value = 0;
        if (e.detail) {
            value = 1;
        } else {
            value = 0;
        }
        this.setData({
            [`modalBox.${field}`]: value
        });
    },

    bindQrcode(e) {
        if (e.detail.confirm) {
            //判断一下需要填手机号
            colorUISdk.request({
                url: 'api/user/bind_qrcode',
                method: 'POST',
                data: {
                    from: this.data.modalBox, //二维码id
                }
            }).then(res => {
                if (res.code === 1) {
                    this.setData({
                        modalBox: {
                            qrcode_id: res.data.id,
                            phone: res.data.phone,
                            backup_phone: res.data.backup_phone,
                            wx_notice: res.data.wx_notice,
                            is_privacy: res.data.is_privacy,
                        }
                    })
                    this.setData({
                        qrcodeInfo: res.data
                    });

                    this.getUserInfo();

                    //3秒后提示
                    setTimeout(() => {
                        this.setData({
                            notify: {
                                show: true,
                                msg: '绑定成功',
                                bg: 'bg-green',
                                type: 3,
                                align: 'center',
                            }
                        })
                    }, 1500);

                } else {

                    this.setData({
                        qrcodeInfo: {},
                        modalBox: {},
                    });

                    wx.showToast({
                        title: res.msg,
                        duration: 3000,
                        icon: 'error'
                    })
                }
            }).catch(err => {
                this.setData({
                    qrcodeInfo: {},
                    modalBox: {},
                });

                wx.showToast({
                    title: '系统异常！',
                    duration: 3000,
                    icon: 'error'
                })

            })
        } else {
            this.setData({
                qrcodeInfo: {},
                modalBox: {},
            });

            wx.showToast({
                title: '已放弃修改！请重新扫码',
                duration: 3000,
                icon: 'error'
            })

        }

    },
    send_subscribe_message(e) {
        if (e.detail.confirm) {
            if (this.data.send_mode.send_msg === '') {
                wx.showToast({
                    title: '请输入发送内容',
                    duration: 3000,
                    icon: 'error'
                })
                return;
            }
            const phone = this.data.send_mode.phone.trim();
            /*校验手机号格式*/
            // 非空判断
            if (!phone) {
                wx.showToast({
                    title: '请输入手机号',
                    duration: 3000,
                    icon: 'error'
                });
                return;
            }

            // 正则格式判断（中国大陆手机号：1 开头 + 10 位数字）
            const phoneRegex = /^1[3-9]\d{9}$/;

            if (!phoneRegex.test(phone)) {
                wx.showToast({
                    title: '手机号格式不正确,请重新填写',
                    duration: 3000,
                    icon: 'error'
                });
                return;
            }


            // 用户点击了确认按钮
            // 这里写发送通知的代码
            colorUISdk.request({
                url: 'api/user/send_subscribe_message',
                method: 'POST',
                data: {
                    'send_msg': this.data.send_mode.send_msg,
                    'phone': phone,
                    //经纬度
                    'lat': this.data.latitude,
                    'lng': this.data.longitude,
                    'to_user_id': this.data.qrcodeInfo.user_id
                }
            }).then(res => {

                if (res.code === 1) {
                    this.setData({
                        modal: {
                            show: true,
                            title: '成功',
                            content: res.msg
                        }
                    })

                    if (this.data.userInfo.id === this.data.qrcodeInfo.user_id) {
                        app.userInfo.wx_notice = 0;
                    }

                } else {
                    this.setData({
                        modal: {
                            show: true,
                            title: '失败',
                            content: res.msg
                        }
                    })
                    /*wx.showToast({
                        title: '车主未开启微信消息订阅,请使用其他方法联系',
                        duration: 3000,
                        icon: 'error'
                    })*/

                }
            }).catch(err => {
                wx.showToast({
                    title: '未开启消息提醒',
                    duration: 3000,
                    icon: 'error'
                })
            })

        }

    },
    getUserLocation() {
        wx.getLocation({
            type: 'gcj02',
            success: (res) => {
                console.log('当前位置', res.latitude, res.longitude);
                this.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            },
            fail: function (res) {
                console.log('获取位置失败', res);
            }
        });
    },

    subscribe() {
        wx.requestSubscribeMessage({
            tmplIds: ['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'],
            success: res => {
                if (res['nGA2V4J7bVeuKS7xiu4RsAsw91BEB45N13sJ_VNpQmQ'] === 'accept') {
                    colorUISdk.request({
                        url: 'api/user/change_wx_notice',
                        method: 'POST',
                        data: {wx_notice: 1}
                    }).then(res => {
                        if (res.code === 1) {
                            this.setData({
                                subscribe_modal: {
                                    show: true,
                                    title: '订阅成功',
                                    content: res.msg
                                }
                            });
                            this.setUserInfo(res.data);
                        } else {
                            wx.showToast({title: res.msg, icon: 'none'});
                        }
                    });
                }
            }
        });
    },

    getPhoneNumber() {
        colorUISdk.request({
            url: 'api/user/info',
            method: 'GET',
            data: {}
        }).then(res => {
            console.log(res)
        }).catch(err => {
            console.log(err)
        })
    },


    showCall(e) {
        if (e.detail.confirm) {
            let phone = e.currentTarget.dataset.phone;
            if (!phone) {
                wx.showToast({
                    title: '未设置电话,请使用其他方式~',
                    icon: '_icon-warn-o'
                });
            }


            colorUISdk.request({
                url: 'api/user/bind_phone',
                method: 'POST',
                data: {
                    phone: phone
                }
            }).then(res => {
                console.log(res)
                if (res.code === 1) {
                    wx.makePhoneCall({
                        phoneNumber: res.data.phone
                    });
                } else {
                    this.setData({
                        modal: {
                            show: true,
                            title: '失败',
                            content: res.msg
                        }
                    })
                }
            }).catch(err => {
                console.log(err)
                wx.showToast({
                    title: '系统错误',
                    icon: '_icon-close'
                })
            })


        }
    },
    scan() {
        wx.scanCode({
            success: res => {
                if (res.path) {
                    const scene = decodeURIComponent(res.path.split('scene=')[1] || '');
                    const qrcode_id = scene.split('qrcode_id=')[1];

                    const user_id = scene.split('user_id=')[1];

                    //获取手机号
                    this.getPhoneNumber();
                    if (qrcode_id) {
                        //获取小程序码的信息
                        this.getQrcodeDetail(qrcode_id);
                    } else {
                        if (user_id) {
                            this.getTestQrcodeDetail(user_id);
                        } else {
                            wx.showToast(
                                {
                                    title: '无效的小程序码',
                                    icon: '_icon-warn-o'
                                }
                            );
                        }
                    }
                }
            }
        })
    },
    success(res) {
        const {
            detail
        } = res
        console.log(detail);
    },
    showCustomizeModal(e) {
        if (e.currentTarget.dataset.key === 'wx_notice') {
            //获取定位
            this.getUserLocation();
        }

        this.setData({
            target: e.currentTarget.dataset.key
        })
    },
    // 监听用户滑动页面事件。
    onPageScroll(e) {
        // 注意：请只在需要的时候才在 page 中定义此方法，不要定义空方法。以减少不必要的事件派发对渲染层-逻辑层通信的影响。
        // 注意：请避免在 onPageScroll 中过于频繁的执行 setData 等引起逻辑层-渲染层通信的操作。尤其是每次传输大量数据，会影响通信耗时。
        // https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#onPageScroll-Object-object
        this.setData({
            scrollTop: e.scrollTop
        })
    }
})